#include "user_threads.h"
#include "user_io.h"
#include "user_mutex.h"

#include <stdio.h>
#include <stdlib.h>

int global = 0;

int run_thread(void* arg){
    int* pipe = (int*)arg;
    char buf[5];
    char result[50];
    int i;
    thread_id tid = uthread_self();
    for (i=0; i<10; i++){
        uthread_read(pipe[0], buf, 5);
        sprintf(result,"Thread Id=%d global=%d got from pipe %s\n",
                tid, global, buf);
        uthread_write(0, result, 50);
        global++;
        sprintf(buf,"%d",tid);
        uthread_write(pipe[1], buf, 5);
        uthread_yield();
    }
    return tid;
}

#define N 20

int main(){
    int pipes[2];
    int i;
    thread_id tid = uthread_self();
    char buf[5];
    sprintf(buf,"%d",tid);
    if (uthread_pipe(pipes)==-1){
        printf("couldn't open pipe\n");
        exit(-1);
    }
    for (i=1; i<N; i++){
        uthread_create(run_thread,(void*)pipes);
    }
    uthread_write(pipes[1], buf, 5);
    uthread_yield();
    return run_thread((void*)pipes);
}
